import mysql from 'mysql2'
import { MYSQL_PORT, MYSQL_HOST, MYSQL_DATABASE, MYSQL_PASSWORD, MYSQL_USER } from '../app/app.config';

// 创建连接池，设置连接池的参数
export const appPool = mysql.createPool({
  host: MYSQL_HOST,
  port: parseInt(MYSQL_PORT, 10) || 3306,
  user: MYSQL_USER,
  password: MYSQL_PASSWORD,
  database: MYSQL_DATABASE,
  waitForConnections: true,
  connectionLimit: 10,
  maxIdle: 10, // max idle connections, the default value is the same as `connectionLimit`
  idleTimeout: 60000, // idle connections timeout, in milliseconds, the default value 60000
  queueLimit: 0,
  enableKeepAlive: true,
  keepAliveInitialDelay: 0,
  decimalNumbers: true,
});

/**
 * 执行增删改语句
 * @param sql 增删改语句
 * @param values 参数
 * @param pool 默认参数
 * @returns 执行结果
 */
export function prepareExecute(sql, values, pool = appPool) {
  return new Promise((resolve, reject) => {
    pool.getConnection((err, connection) => {
      if (err) {
        reject(err);
      }
      connection.execute(sql, values, (err, result, fields)=> {
        connection.release()
        if (err) {
          reject(err); 
        }
        resolve(result)
      });
    })
  })
}